import { ActionConstant } from '../actions/search_action';
import { initState, reduceEditState } from './search_reducer';
import { Map } from 'immutable'

export default function search_operator(state, action) {
    let key = '';
    switch (action.type){
        case ActionConstant.type_editor_operator_exact:
            return editInput(state, action, 'exact_match');
        case ActionConstant.type_editor_operator_subtract:
            return editInput(state, action, 'subtract');
        case ActionConstant.type_editor_operator_synonyms:
            return editInput(state, action, 'synonyms');
        case ActionConstant.type_editor_operator_may:
            return editInput(state, action, 'may');
        case ActionConstant.type_editor_operator_from:
            let range = state.get('content').get('range').set('from', action.value);
            let content = state.get('content');
            content = content.set('range', range);
            return state.set('content', content);
        case ActionConstant.type_editor_operator_to:
            range = state.get('content').get('range').set('to', action.value);
            content = state.get('content');
            content = content.set('range', range);
            return state.set('content', content);
        case ActionConstant.type_clear_operator:
            return Map(initState.search_operator);
        default:
            if(!state)
                return Map(initState.search_operator);
            return state;
    }
}

function editInput(state, action, key) {
    let data = state.get('content').get(key);
    data = reduceEditState(data, action.former_text, action.current_text, action.index);
    let new_content = state.get('content').set(key, data);
    return state.set('content', new_content);
}